<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/3/20
 * Time: 21:15
 */


namespace app\index\controller;

use app\common\controller\HomeBase;
use app\common\model\BoolStatus;
use app\common\model\FavoritesItem as FavoritesItemModel;
use tbk\top\request\TbkItemRecommendGetRequest;
use think\Cache;
use think\Config;
use tbk\top\TopClient;
use app\common\model\FavoritesItem;

class Shopping extends HomeBase
{

    /**
     * 缓存前缀
     * @var string
     */
    private $_cachePrefix = 'goods_';


    /**
     * 缓存时间
     * @var int
     */
    private $_cacheExpire = 3600;


    /**
     * 默认入口
     * @return mixed
     */
    public function index()
    {
        $currentPage = $this->request->param('page', 1, 'int');
        $price = $this->request->param('price', '');
        $firstPrice = $secondPrice = 0;
        if ($price) {
            $priceArr = explode('_', $price);
            $priceNum = count($priceArr);
            if ($priceNum > 1) {
                list($firstPrice, $secondPrice) = $priceArr;
            } elseif ($priceNum == 1) {
                list($firstPrice) = $priceArr;
            }
        }


        $favoritesItemModel = new FavoritesItemModel();
        $this->pageSize     = 40;
        $query               = $favoritesItemModel->where('status', '=', BoolStatus::OPEN);
        if ($firstPrice) {
            $query->where('zk_final_price', '>=', $firstPrice);
        }
        if ($secondPrice) {
            $query->where('zk_final_price', '<', $secondPrice);
        }
        $list = $query->order('id', 'DESC')
            ->paginate($this->pageSize, false, [
                'page' => $currentPage,
                'query' => ['price' => $price]
            ]);
        $page               = $list->render();
        $this->assign('list', $list->getCollection());
        $this->assign('page', $page);
        $this->assign('currentPage', $list->currentPage());
        $this->assign('price', $price);

        $screenList = [
            [
                'name' => '价格',
                'screen' => [
                    ['value' => '', 'label' => '全部'],
                    ['value' => '0_49', 'label' => '0-49'],
                    ['value' => '50_99', 'label' => '50-99'],
                    ['value' => '100_149', 'label' => '100-149'],
                    ['value' => '150_199', 'label' => '150-199'],
                    ['value' => '200_249', 'label' => '200-249'],
                    ['value' => '250_299', 'label' => '250-299'],
                    ['value' => '300_399', 'label' => '300-399'],
                    ['value' => '400_499', 'label' => '400-499'],
                    ['value' => '500', 'label' => '500以上'],
                ],
            ],
        ];
        $this->assign('screenList', $screenList);

        $desc = $keywords = '时尚女装|学生装|夏装|连衣裙|长裙|短裙|衬衫|打底裙|t恤|雪纺衫|针织衫|牛仔裤|卫衣|运动服|小西装';
        $this->setSEOInfo('购物中心', $keywords, $desc);
        return $this->fetch('shopping/index');
    }

    public function getList()
    {
        $page = max(1, $this->request->param('page'));

    }


    /**
     * 商品详情
     * @param int $id
     */
    public function item($id = 1)
    {
        $model = Cache::get($this->_cachePrefix . $id);
        if (!$model) {
            $model = FavoritesItemModel::find($id);
            if (!$model) {
                abort(404);
            }
            Cache::set($this->_cachePrefix . $id, $model, $this->_cacheExpire);
        }

        $small_images  = unserialize($model->small_images);
        $saveMoneyTxt = '';
        if ($model->reserve_price >  $model->zk_final_price) {
            $saveMoneyTxt = '可节省￥'.bcsub($model->reserve_price, $model->zk_final_price, 2) .'/';
        }

        $recommendGoodsList = (new FavoritesItem())->getRandRecommendData(4);
        $this->assign('recommendGoodsList', $recommendGoodsList);

        $title         = $model->title;
        $this->assign('small_images', $small_images);
        $this->assign('item', $model);
        $this->assign('name', $title);
        $this->setSEOInfo($saveMoneyTxt .$title, $title, $title);
        return $this->fetch('shopping/item');
    }


    /**
     * 淘宝客商品关联推荐查询
     * @param $numIid 商品ID
     */
    private function _getRecommendItem($numIid, $id, $count = 6)
    {
        $favoritesItemModel = new FavoritesItemModel();
        $recommendItem      = $favoritesItemModel->where('status', '=', BoolStatus::OPEN)
            ->where('pid', '=', $id)
            ->order('id', 'DESC')
            ->limit($count)
            ->select();
        if (!$recommendItem) {
            $config       = Config::get('tbk');
            $appkey       = $config['appkey'];
            $secret       = $config['secret'];
            $c            = new TopClient;
            $c->appkey    = $appkey;
            $c->secretKey = $secret;
            $req          = new TbkItemRecommendGetRequest();
            $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url,volume");
            $req->setNumIid($numIid);
            $req->setCount($count);
            $req->setPlatform("1");
            $resp = $c->execute($req);

            $favoritesItemModel = new FavoritesItemModel();
            $results            = $resp->results;
            foreach ($results as $n_tbk_item) {
                foreach ($n_tbk_item as $item) {
                    $item  = (array)$item;
                    $count = $favoritesItemModel->where('num_iid', '=', $item['num_iid'])->count();
                    if (!$count) {
                        $small_images = isset($item['small_images']) ? (array)$item['small_images']->string : [];
                        $data         = [
                            'num_iid'            => $item['num_iid'],
                            'title'              => $item['title'],
                            'pict_url'           => $item['pict_url'],
                            'small_images'       => serialize($small_images),
                            'reserve_price'      => $item['reserve_price'],
                            'user_type'          => $item['user_type'],
                            'provcity'           => $item['provcity'],
                            'item_url'           => $item['item_url'],
                            'volume'             => $item['volume'],
                            'zk_final_price'     => $item['zk_final_price'],
                            'zk_final_price_wap' => $item['zk_final_price'],
                            'favorites_id'       => 0,
                            'created_time'       => date('Y-m-d H:i:s', time()),
                            'pid'                => $id,
                        ];
                        $favoritesItemModel->insert($data);
                    }
                }
            }
            $recommendItem = $favoritesItemModel->where('status', '=', BoolStatus::OPEN)
                ->where('pid', '=', $id)
                ->order('id', 'DESC')
                ->limit($count)
                ->select();
        }
        $this->assign('RecommendItem', $recommendItem);
    }
}